package com.navinfo.opentsp.platform.computing.analysis.entity.cleanAsh;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class AshLoadingsInfo {
    private static final int SAVE_SIZE = 200;
    /**
     * 保存最后SAVE_SIZE个有效的灰载量
     */
    private int[] ashLoads = new int[SAVE_SIZE];
    private int counter = 0;
    private long tid;

    public void push(Integer ashLoad) {
        if (ashLoad != null) {
            ashLoads[counter % SAVE_SIZE] = ashLoad;
            counter++;
        }
    }

    public int[] peek(int n) {
        int[] res;
        if (counter <= SAVE_SIZE) {
            res = new int[n < counter ? n : counter];
            for (int i = 0; i < res.length; i++) {
                res[i] = ashLoads[i];
            }
        } else {
            res = new int[n < SAVE_SIZE ? n : SAVE_SIZE];
            int readIndex = counter;
            for (int i = 0; i < res.length; i++) {
                res[i] = ashLoads[readIndex % SAVE_SIZE];
                readIndex++;
            }
        }
        return res;
    }

    public void clear() {
        for (int i = 0; i < SAVE_SIZE; i++) {
            ashLoads[i] = 0;
        }
    }

    public String getAshLoads() {
        final String delimiter = ",";
        if (counter <= SAVE_SIZE) {
            return IntStream.of(ashLoads).limit(counter).mapToObj(String::valueOf).collect(Collectors.joining(delimiter));
        }
        List<String> s = new ArrayList<>();
        int readIndex = counter;
        for (int i = 0; i < SAVE_SIZE; i++) {
            s.add(String.valueOf(ashLoads[readIndex % SAVE_SIZE]));
            readIndex++;
        }
        return String.join(delimiter, s);
    }

    public void setAshLoads(String ashLoads) {
        if (ashLoads != null && !"".equals(ashLoads)) {
            String[] newValues = ashLoads.split(",");
            int i = 0;
            for (; i < SAVE_SIZE && i < newValues.length; i++) {
                this.ashLoads[i] = tryParse(newValues[i]);
            }
            counter = i;
        } else {
            counter = 0;
        }
    }

    public long getTid() {
        return tid;
    }

    public void setTid(long tid) {
        this.tid = tid;
    }

    private int tryParse(String s) {
        try {
            return Integer.parseInt(s);
        } catch (Exception e) {
            return 0;
        }
    }
}
